function hfile = amr_InterpolateTo256x256(hfile, method)
% AMR::InterpolateTo256x256  - interpolate the AMR to a 256x256 matrix
%
% FORMAT:       amr.InterpolateTo256x256([method])
%
% Input fields:
%
%       method      string: 'neareast', {'linear'}, 'cubic'
%
% No output fields.

% Version:  v0.7b
% Build:    7083008
% Date:     Aug-30 2007, 8:51 AM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'amr')
    error( ...
        'BVQXfile:BadArguments', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
if nargin < 2 || ...
   ~ischar(method) || ...
    isempty(method) || ...
    ~any(strcmpi(method(:)', {'nearest', 'linear', 'cubic'}))
    method = 'linear';
end
method = lower(method(:)');

% check AMR size
sc = bvqxfile_getscont(hfile.L);
bc = sc.C;
asz = size(bc.Slice(1).AMRData);
nsl = numel(bc.Slice);
for sc = 1:nsl
    if numel(size(bc.Slice(sc).AMRData)) ~= 2 || ...
        any(asz ~= size(bc.Slice(sc).AMRData))
        error( ...
            'BVQXfile:BadObject', ...
            'AMR slices are not equally sized.' ...
        );
    end
end

% interpolation needed?
if all(asz == 256)
    return;
end

% build grid coordinates
[nx, ny] = ...
    meshgrid(1:((asz(1) - 1) / 255):asz(1), 1:((asz(2) - 1) / 255):asz(2));

% interpolate data and new settings
for sc = 1:nsl
    slc = bc.Slice(sc);
    slcd= uint8(interp2(double(slc.AMRData), nx, ny, method));
    slcd(slcd > 225) = 225;
    slc.AMRData = slcd;
    slc.BITMAPFILEHEADER.bfSize = 65536 + slc.BITMAPFILEHEADER.bfOffBits;
    slc.BITMAPINFOHEADER.biWidth = 256;
    slc.BITMAPINFOHEADER.biHeight = 256;
    slc.BITMAPINFOHEADER.biImageSize = 65536;
    bc.Slice(sc) = slc;
end

% clear filename and set back to array
sc.F = '';
bvqxfile_setscont(hfile.L, sc);
